package com.example.chatroom.service.impl;

import com.example.chatroom.common.errorcode.ServiceErrorCodeConstants;
import com.example.chatroom.common.exception.ServiceException;
import com.example.chatroom.common.utils.JWTUtil;
import com.example.chatroom.dao.dataobject.FriendDO;
import com.example.chatroom.dao.dataobject.UserDO;
import com.example.chatroom.dao.mapper.FriendMapper;
import com.example.chatroom.dao.mapper.UserMapper;
import com.example.chatroom.service.IFriendService;
import com.example.chatroom.service.dto.FriendListDTO;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class FriendServiceImpl implements IFriendService {
    @Autowired
    private FriendMapper friendMapper;
    @Autowired
    private JWTUtil jwtUtil;
    @Autowired
    private UserMapper userMapper;
    @Override
    public List<FriendListDTO> getFriendList(HttpServletRequest request) {
        //1-    判断user_token是否存在
        String userToken=request.getHeader("user_token");
        if(!StringUtils.hasLength(userToken)){
            log.info(ServiceErrorCodeConstants.USER_TOKEN_NOT_EXISTS.getMsg());
            throw new ServiceException(ServiceErrorCodeConstants.USER_TOKEN_NOT_EXISTS);
        }
        //2-    校验令牌是否合法
        Claims verify = jwtUtil.verify(userToken);
        if(verify==null){
            log.error("Token非法 user_token:{}",userToken);
            throw new ServiceException(ServiceErrorCodeConstants.USER_TOKEN_UNLAWFUL);
        }
        //3-    获取当前用户id
        Map<String, Object> tokenInfo = jwtUtil.getTokenInfo(userToken);
        Object userIdObj = tokenInfo.get("userId");
        Long userId= jwtUtil.getUserId(userToken);

        //4-    根据用户id获取朋友列表
        List<FriendDO> friendDOS=friendMapper.selectByUserId(userId);
        return friendDOS.stream().map(friendDO -> {
            FriendListDTO friendListDTO=new FriendListDTO();
            friendListDTO.setUserId(friendDO.getUserId());
            friendListDTO.setFriendId(friendDO.getFriendId());
            UserDO userDO = userMapper.selectByPrimaryKey(friendDO.getFriendId());
            friendListDTO.setFriendName(userDO.getUserName());
            return friendListDTO;
        }).collect(Collectors.toList());
    }
}
